package cn.itsource.pethome.user.controller;


import cn.itsource.pethome.user.domain.User;
import cn.itsource.pethome.user.service.IUserService;
import cn.itsource.pethome.utils.AjaxResult;
import cn.itsource.pethome.utils.RedisUtils;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService userService;

    @PostMapping("/checkPhone")
    public AjaxResult checkPhone(@RequestBody Map<String,String> map){
        try {
            String phone = map.get("phone");
            userService.checkPhone(phone);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(e.getMessage());
        }
    }

    @PostMapping("/sendMobileCode")
    public AjaxResult sendMobileCode(@RequestBody Map<String,String> map){
        String phone = map.get("phone");
        return userService.sendMobileCode(phone);
    }

    @PostMapping("/register")
    public AjaxResult register(@RequestBody Map<String,String> map){
        String code = map.get("code");
        User user = new User();
        user.setPassword(map.get("password"));
        user.setPhone(map.get("phone"));
        return userService.register(code,user);
    }

    @PostMapping("/login")
    public AjaxResult login(@RequestBody User user){
        try {
            User loginUser = userService.login(user);
            //如果登录成功，则生成一个令牌(token)响应到前端
            //token使用UUID生成
            String token = UUID.randomUUID().toString();

            //由于redis中只能存字符串，所以将对象转换为json格式的字符串(因为以后可能需要取出来再装换为对象)
            //将token存入redis中并设置过期时间
            RedisUtils.INSTANCE.set(token, JSONObject.toJSONString(loginUser), 60*30);

            //将用户名和密码也发送过去，让其保存
            //由于需要返回多个数据，而AjaxResult只能携带一个数据过去，所以我们使用map装起来
            Map<String, Object> map = new HashMap<>();
            map.put("token", token);
            map.put("loginUser", loginUser);
            return AjaxResult.me().setResultObj(map);
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(e.getMessage());
        }
    }
}
